<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 18-12-29
 * Time: 上午10:16
 */

namespace app\components\exceptions;


use app\common\Helpers;
use Yii;
use yii\web\Response;

trait Handle
{

    public function handle(\Throwable $e)
    {
        if ($e instanceof Exception) {
            $message = $e->getMsg();
        } else {
            $message = $e->getMessage();
        }
        $code=$e->getCode()?:-1;

        $message=[
            'msg'  => $message,
            'file'    => $e->getFile(),
            'line'   => $e->getLine()
        ];

        $this->showMessage($code, $message);

    }

    /**
     * 展示异常信息
     * @param $code
     * @param $message
     */
    protected function showMessage($code,$message)
    {
        $message = is_array($message) ? json_encode($message, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE):$message;
        $response=Yii::$app->response;

        if(Yii::$app->request->isAjax){
            $response->format=Response::FORMAT_JSON;
            $response->data=Helpers::webJson($code, $message);
        }else{
            $response->data = "异常页面展示<br>" . $message;
        }

        //终止程序
        Yii::$app->end(0,$response);

    }

}